import 'dart:convert';
import 'dart:typed_data';

import 'package:audio_session/audio_session.dart';
import 'package:flutter_sound/flutter_sound.dart';


class SoundDemo {
  static late final SoundDemo instance = SoundDemo._();

  SoundDemo._();

  final FlutterSoundPlayer _player = FlutterSoundPlayer();

  Future<void> initPlayer() async {
    await _player.openPlayer();
    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
      AVAudioSessionCategoryOptions.allowBluetooth |
      AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
      AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
  }

  /// 开始流式播放
  Future<void> startStreamPlayer() async {
    await _player.startPlayerFromStream(
        codec: Codec.pcm16,
        numChannels: 1,
        sampleRate: 16000,
        // interleaved: false,
        // bufferSize: 100,
        whenFinished: () {
          print("播放结束");
        }
    );
    _player.setVolume(1);
    // _player.setSpeed(speed)
  }

  /// 向播放器写入一段数据（服务端推送到客户端时调用）
  void feedAudioChunk(Uint8List audioBytes) {
    FoodData food = FoodData(audioBytes);
    // _player.feedFromStream(audioBytes);
    _player.foodSink?.add(food);
  }

  /// 停止播放
  Future<void> stopStreamPlayer() async {
    await _player.foodSink?.close(); // 通知数据结束
    await _player.stopPlayer();
  }

}